package com.ptszyxx.popose.module.main.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.enums.RankEnum;
import com.ptszyxx.popose.common.enums.RankItemEnum;
import com.ptszyxx.popose.databinding.FragmentHomeRankDataBinding;
import com.ptszyxx.popose.module.main.home.adapter.HomeRankAdapter;
import com.ptszyxx.popose.module.main.home.vm.HomeRankDataVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.home.HomeRankEntity;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YRecyclerViewUtil;

import java.util.List;

/**
 *
 */
public class HomeRankDataFragment extends BaseFragment<FragmentHomeRankDataBinding, HomeRankDataVM> {
    private HomeRankAdapter adapter;
    private String name;
    private RankEnum rankEnum;

    public HomeRankDataFragment(){}

    public HomeRankDataFragment(String name, RankEnum rankEnum){
        this.name = name;
        this.rankEnum = rankEnum;
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_home_rank_data;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public HomeRankDataVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(HomeRankDataVM.class);
    }

    @Override
    public void initParam() {
        super.initParam();
        viewModel.rankEnum = rankEnum;
        viewModel.rankItemEnum = RankItemEnum.get(name);
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
        adapter = new HomeRankAdapter(viewModel, rankEnum);
        YRecyclerViewUtil.init(getContext(), binding.recyclerView, adapter);
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestRank();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, new Observer<List<HomeRankEntity>>() {
            @Override
            public void onChanged(List<HomeRankEntity> list) {
                setAdapterUI(list);
                adapter.setList(list);
            }
        });
    }

    private void setAdapterUI(List<HomeRankEntity> list) {
        if (YCollectionUtil.isNotEmpty(list)){
            binding.stateLayout.showContent();
            adapter.setList(list);
        }else{
            binding.stateLayout.showEmpty();
        }
    }
}
